package com.liuyz.tcp_;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP数据交互_字节流 {

    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);

        // 获取数据
        Socket socket = serverSocket.accept(); // 暂停/
        InputStream inputStream = socket.getInputStream();
        byte[] arr = new byte[1024];
        int len;
        while ((len = inputStream.read(arr)) != -1) {
            System.out.print(new String(arr, 0, len));
        }
        socket.shutdownInput(); // socket结束写入标记

        // 发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,client".getBytes());

        socket.shutdownOutput(); // socket结束写出标记

        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }

    @Test
    public void client() throws IOException {
        // 发送数据
        Socket socket = new Socket("127.0.0.1", 9999);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,server".getBytes());
        socket.shutdownOutput(); // socket结束写出标记

        // 接收数据
        InputStream inputStream = socket.getInputStream();
        byte[] arr = new byte[1024];
        int len;
        while ((len = inputStream.read(arr)) != -1) {
            System.out.print(new String(arr, 0, len));
        }
        socket.shutdownInput(); // socket结束写入标记

        inputStream.close();
        outputStream.close();
        socket.close();
    }

}
